package cn.tedu.charging.order.config;


import cn.tedu.charging.order.mqtt.MqttConsumer;
import cn.tedu.charging.order.mqtt.MqttContext;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class MqttConfiguration {
    @Autowired
    private MqttContext mqttContext;

    private  final String host = "tcp://127.0.0.1:1883";
    private  final String userName = "admin";
    private  final String password = "public";
    private  final String clientId = "order_service_client"+Math.random();

    @Bean
    public MqttClient mqttClient() throws Exception{
        MqttClient mqttClient = new MqttClient(host,clientId);
        MqttConnectOptions options=new MqttConnectOptions();
        options.setUserName(userName);
        options.setPassword(password.toCharArray());
        options.setCleanSession(true);
        options.setAutomaticReconnect(true);
        options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
        //创建一个实现了 MqttCallbackExtended接口的 callback 回调对象
        //通过 Java new 创建出的对象 没有在Spring容器中
        MqttConsumer mqttConsumer = new MqttConsumer(mqttClient,mqttContext);
        //set写方法，把mqttClient 传入进去
        //mqttConsumer.setMqttClient(mqttClient);
        //这里的代码是 主动调用connectComplete连接成功的方法，没有真的连接成功
        //mqttConsumer.connectComplete(false, host);
        //设置回调
        mqttClient.setCallback(mqttConsumer);
        //通过连接的配置和EMQX进行连接
        mqttClient.connect(options);
        log.debug("MQTT客户端准备和EMQX连接");
        return mqttClient;
    }
}
